<?php
declare (strict_types = 1);

namespace app\command\region;

use think\console\Input;
use think\console\Output;
use think\console\Command;
use think\facade\Db;

/**
 * 国家统计局省市区
 *
 * Class NationalBureauRegion
 * @package app\command\national\region
 */
class NationalBureauRegion extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('national bureau region')
            ->setDescription('国家统计局统计用区划和城乡划分代码获取');
    }

    protected function execute(Input $input, Output $output)
    {
        $regions = json_decode(file_get_contents(__DIR__ . '/region.json'), true);

        $insert = [];
        foreach ($regions as $region) {
            $insert[] = [
                'code' => $region['code'],
                'p_code' => 0,
                'name' => $region['name'],
            ];

            if (!empty($region['child'])) {
                foreach ($region['child'] as $child) {

                    if ('市辖区' == $child['name']) {
                        $child['name'] = $region['name'];
                    }
                    $insert[] = [
                        'code' => $child['code'],
                        'p_code' => $region['code'],
                        'name' => $child['name'],
                    ];

                    if (!empty($child['child'])) {
                        foreach ($child['child'] as $grandson) {
                            $insert[] = [
                                'code' => $grandson['code'],
                                'p_code' => $child['code'],
                                'name' => $grandson['name'],
                            ];
                        }
                    }
                }
            }
        }
        Db::connect('communal')->table('91000_region')->insertAll($insert);
        // 指令输出
        $output->writeln('done');
    }
}
